package com.qf.user.factory.loginfactory;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qf.common.core.entity.User;
import com.qf.common.core.utils.JwtUtils;
import com.qf.user.mapper.UserMapper;
import com.qf.user.param.LoginParam;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zdl
 * @date 2025/3/22
 */
@Service
public class UserNameAndPassWordLoginRation implements LoginRation{
    @Resource
    private UserMapper userMapper;
    @Override
    public String login(LoginParam loginParam) { //必传参数username,password,loginType =1
        User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getUsername, loginParam.getUsername()));
        if (user == null) {
            throw new RuntimeException("用户名错误");
        }
        // 前端传过来的是明文密码，数据库存储的是MD5加密的密码，所以需要对前端传过来的密码进行加密再与数据库中的密码进行比较
        String md5Pwd = SecureUtil.md5(loginParam.getPassword());
        if (!(user.getPassword().equals(md5Pwd))) {
            throw new RuntimeException("密码错误");
        }
        //返回token  使用jwt作为token的生成方式
        Map<String, Object> map = new HashMap<>();
        map.put("uid", user.getId());
        return JwtUtils.createJwt(map);
    }
}
